package com.leen.admin.service.impl;

import com.leen.admin.dto.RoleDto;
import com.leen.admin.dto.RoleSaveDTO;
import com.leen.admin.entity.Role;
import com.leen.admin.repository.RoleRepository;
import com.leen.admin.service.RoleService;
import com.leen.common.util.DateTimeUtil;
import com.leen.common.vo.ResponseVO;
import com.leen.security.CurrentAdminInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor=Exception.class)
@Service
public class RoleServiceImpl extends CurdServiceImpl<Role,Integer> implements RoleService {


    private RoleRepository roleRepository;

    @Autowired
    public void setRoleRepository(RoleRepository roleRepository){
        this.roleRepository = roleRepository;
        //给父类赋值
        super.setCrudRepository(roleRepository);
    }


    @Override
    public ResponseVO search(RoleDto roleDto) {

        //分页页码
        Pageable pageable = PageRequest.of(roleDto.getPageNumber()-1,roleDto.getPageSize());
        //构建查询对象
        Specification<Role> specification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //创建一个Predicate的集合
                List<Predicate> arr = new ArrayList<>();
                if (StringUtils.isNotBlank(roleDto.getRoleName())){
                    arr.add(criteriaBuilder.like(root.get("roleName"),"%"+roleDto.getRoleName()+"%"));
                }

                if (roleDto.getStartTime()!=null &&  roleDto.getEndTime()!=null){
                    //结束日期+1  2021-04-06 00:00:00  ~  2021-04-06 23:59:59
                     roleDto.setEndTime( DateTimeUtil.dateToEnd(roleDto.getEndTime()));
                    arr.add(criteriaBuilder.between(root.get("createTime"),roleDto.getStartTime(),roleDto.getEndTime()));
                }

                if(roleDto.getStatus()!=null){
                    arr.add(criteriaBuilder.equal(root.get("status"),roleDto.getStatus()));
                }

                return criteriaBuilder.and(arr.toArray(new Predicate[arr.size()]));
            }
        };
        //查询
        Page<Role> page = this.roleRepository.findAll(specification, pageable);
        return new ResponseVO(page.getTotalElements(),page.getContent());
    }

    @Override
    public boolean save(RoleSaveDTO roleSaveDTO) {
        Role dbRole=new Role();
        String userName= CurrentAdminInfo.getAdminLoginUserDetails().getUsername();
        //修改
        if(roleSaveDTO.getRoleId()!=null){
            // 删除sys_role_menu所有关于它的菜单
            this.roleRepository.deleteByRoleId(roleSaveDTO.getRoleId());
            //修改本身的值
            dbRole=this.roleRepository.findById(roleSaveDTO.getRoleId()).get();

        }else{
            dbRole.setCreateBy(userName );
            dbRole.setCreateTime(new Date());
        }

        //复制新的值
        BeanUtils.copyProperties(roleSaveDTO,dbRole,"roleId");


        dbRole.setUpdateBy(userName );
        dbRole.setUpdateTime(new Date());

        this.roleRepository.save(dbRole);

        // 批量保存权限  sys_role_menu
        if(roleSaveDTO.getMenuIds()!=null && roleSaveDTO.getMenuIds().size()>0){
            for(int menuId: roleSaveDTO.getMenuIds()){
               this.roleRepository.insertBatch( dbRole.getRoleId(), menuId);
            }
        }


        return true;
    }
}
